<template>
  <div class="bg">
    <div class="login">
      <div class="title">
        <img :src="logo" />
        <h2>动力港能源管理平台</h2>
      </div>
      <ElForm class="form" :model="form" :rules="rules" ref="fromRef">
        <ElFormItem prop="username">
          <ElInput v-model="form.username" placeholder="请输入用户名" :prefix-icon="User" />
        </ElFormItem>
        <ElFormItem prop="password">
          <ElInput v-model="form.password" placeholder="请输入密码" :prefix-icon="Lock" type="password"/>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" class="btn" @click="handleLogin">登录</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
  </div>
</template>

<script setup lang="ts">
  import logo from '@/assets/logo.png';
import { useUserStore } from '@/store/auth';
  import { User, Lock } from '@element-plus/icons-vue';
  import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';

  interface FormType {
    username: string;
    password: string;
  }

  /** 表单数据 */
  const form: FormType = reactive({
    username: '',
    password: '',
  });

  /** 表单校验规则 */
  const rules = reactive<FormRules<FormType>>({
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 4, max: 8, message: '用户名要求4-8位数字字母组合', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { pattern: /^\d{6}$/, message: '密码必须位6位纯数字', trigger: 'change' },
    ],
  });

  /** 登录功能 */
  const userStore = useUserStore();
  const router = useRouter();
  const fromRef = ref<FormInstance>();
  
  function handleLogin() {
    // 表单项校验
    fromRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        // 校验通过，将请求的数据存储到store中
        await userStore.login(form);
        // 跳转首页
        router.push('/');
      }
    })
  }


</script>

<style scoped lang="scss">
  .bg {
    background-image: url('../../assets/bg.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    height: 100vh;

    .login {
      width: 450px;
      height: 250px;
      padding: 50px;
      box-shadow: 0 0 10px 10px #f4f4f4;
      text-align: center;
      position: absolute;
      top: 50%;
      left: 10%;
      transform: translateY(-50%);

      .title {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 20px;
        margin-bottom: 36px;
        img {
          width: 50px;
          height: 50px;
        }
      }

      .form {
        display: flex;
        flex-direction: column;

        .btn {
          width: 100%;
        }
      }
    }
  }
</style>
